'use strict';
(function(){
    var remoteVideo, localVedio, localStream;
    var config = {"iceServers": [{"urls":"stun:stun.l.google.com:19302"}]};
    var pc1 = new RTCPeerConnection(config), pc2 = new RTCPeerConnection(config);
    var signal = {sendPc1:function(data){
        recv("Pc2", data);
        console.log("pc1"+JSON.stringify(data));
    }, sendPc2:function(data){
        recv("Pc1", data);
        console.log("pc2"+JSON.stringify(data));
    }};

    remoteVideo = document.getElementById('remoteVideo');
    remoteVideo.addEventListener('loadedmetadata', function() {
        console.log('Remote video videoWidth: ' + this.videoWidth + 'px,  videoHeight: ' + this.videoHeight + 'px');
    });
    localVedio = document.getElementById('localVideo');
    localVedio.addEventListener('loadedmetadata', function() {
        console.log('Local video videoWidth: ' + this.videoWidth + 'px,  videoHeight: ' + this.videoHeight + 'px');
    });

    // send any ice candidates to the other peer
    pc1.onicecandidate = function (evt) {
        if (evt.candidate) {
            signal.sendPc1({"candidate":evt.candidate});
        }
    };

    // let the "negotiationneeded" event trigger offer generation
    pc1.onnegotiationneeded = function () {
        pc1.createOffer().then(function (offer) {
            return pc1.setLocalDescription(offer);
        }).then(function () {
            // send the offer to the other peer
            signal.sendPc1({"desc":pc1.localDescription});
        }).catch(function(err){
            console.log(err);
        });
    };

    // send any ice candidates to the other peer
    pc2.onicecandidate = function (evt) {
        if (evt.candidate) {
            signal.sendPc2({"candidate":evt.candidate});
        }
    };

    // let the "negotiationneeded" event trigger offer generation
    pc2.onnegotiationneeded = function () {
        pc1.createOffer().then(function (offer) {
            return pc2.setLocalDescription(offer);
        }).then(function () {
            // send the offer to the other peer
            signal.sendPc2({"desc":pc1.localDescription});
        }).catch(function(err){
            console.log(err);
        });
    };

    // once remote video track arrives, show it in the remote video element
    pc2.ontrack = function (evt) {
        console.log(evt);
        if (evt.track.kind === "video") {
            remoteVideo.srcObject = evt.streams[0];
        }
    };

    pc2.onaddstream = function(evt) {
        console.log(window.URL.createObjectURL(evt.stream), evt.stream);
        remoteVideo.srcObject = evt.stream;
        console.log('pc2: received remote stream');
    };


    navigator.mediaDevices.getUserMedia({audio: true, video: true}).then(function(stream){
        localVedio.srcObject = stream;
        localStream          = stream;
        pc1.addStream(stream);
    }).catch(function(e) {
        console.log('getUserMedia() error: ' + e.name);
    });

    //接收数据的处理
    function recv(spc, message) {
        var pc, handlSend;
        if (spc == "Pc1") {
            pc  = pc1;
            handlSend = signal.sendPc1;
        } else {
            pc  = pc2;
            handlSend = signal.sendPc2;
        }

        if (message.desc) {
            var desc = message.desc;
            // if we get an offer, we need to reply with an answer
            if (desc.type == "offer") {
                pc.setRemoteDescription(desc).then(function () {
                    return pc.createAnswer();
                }).then(function (answer) {
                    return pc.setLocalDescription(answer);
                }).then(function () {
                    handlSend({"desc":pc.localDescription});
                }).catch(function(err){
                    console.log(err);
                });
            } else
                pc.setRemoteDescription(desc).catch(function(err){
                    console.log(err);
                });
        } else {
            pc.addIceCandidate(message.candidate).catch(function(err){
                console.log(err);
            });
        }
    };
})();
